package com.handu.luna.boss.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.validation.Valid;

import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.BossException;
import com.handu.luna.core.domain.goods.Attribute;
import com.handu.luna.core.domain.goods.Category;
import com.handu.luna.core.domain.goods.Attribute.SelectType;

@Controller
@RequestMapping("/goods/attribute*")
public class AttributeController extends BaseController{

	/**
	 * 翻页
	 * @param viewState 需对其进行拆解 最后也需返回
	 * @param pageable
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = {"index","/",""})
	public BossModel index(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable) throws UnsupportedEncodingException{
		return createModel("/goods/attribute/index").add("attributesPage",context.getAttributeRepository().findAll(pageable)).add("viewState", "");
	}
	
	@RequestMapping(value="add")
	public BossModel add(){
		return createAttributeModel(new Attribute(SelectType.ONLY));
	}
	
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){
		return createAttributeModel(context.getAttributeRepository().findOne(id));			
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(String viewState,long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		Category category = context.getCategoryRepository().findByAttributeId(String.valueOf(id));
		if(category ==null){
			context.getAttributeRepository().delete(id);
		}else{
			throw new BossException("商品属性被使用不可移除！");
		}
		
		return createModel("goods/attribute/attributes_table").add("attributesPage",context.getAttributeRepository().findAll(pageable)).add("viewState", viewState);
	}
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	public BossModel save(@Valid final Attribute attribute, final BindingResult bindingResult, RedirectAttributes redirectAttributes){
		if (bindingResult.hasErrors()) {
			return createAttributeModel(null);			
		}
		
		String messageNameCheck;
		List<Attribute> attributeNameCheck;
		if(attribute.getId()==null){
			attributeNameCheck = context.getAttributeRepository().findByName(attribute.getName());
		}else{
			attributeNameCheck = context.getAttributeRepository().findByNameAndId(attribute.getName(), attribute.getId());
		}
		
		if(!attributeNameCheck.isEmpty()){
			messageNameCheck = "属性名称 " + attribute.getName() + " 已存在";
			bindingResult.addError(new FieldError("attribute", "name", messageNameCheck));
			return createAttributeModel(attribute);	
		}
		String newStr = attribute.getInputValues().replaceAll("\r\n", "\n");
		attribute.setInputValues(newStr);
		String message = attribute.getSucessFlashMessage();
		context.getAttributeRepository().save(attribute);
		redirectAttributes.addFlashAttribute("message", message);
		return createModel("redirect:index");
	}
	
	private BossModel createAttributeModel(Attribute attribute){
		BossModel modelAndView = createModel("goods/attribute/info")
				.add("selectTypes", Attribute.SelectType.values());
		if(attribute != null)
			modelAndView.add("attribute",attribute);
		return modelAndView;
	}
}
